package com.qf.business.message.handler;

import com.alibaba.fastjson.JSON;
import com.qf.business.message.entity.Message;
import com.qf.business.message.entity.Rooms;
import com.qf.business.message.entity.User;
import com.qf.business.message.handler.base.BaseMsgChannelHandler;
import com.qf.business.message.utils.RoomUtils;
import com.qf.commons.core.utils.JwtUtils;
import com.qf.data.user.entity.Student;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.kurento.client.WebRtcEndpoint;
import org.springframework.stereotype.Component;

/**
 * 提案SDP消息的处理器
 * author Ken
 * create_time 2023/1/6
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class BaseOfferSdpMsgChannelHandler extends BaseMsgChannelHandler {
    @Override
    protected String action() {
        return "offerSdp";
    }

    @Override
    protected void handler(ChannelHandlerContext ctx, Message msg) {
        //获取课程号
        Long cid = msg.getCid();
        //获取角色
        String role = msg.getRole();
        //获取提案的Sdp
        String offerSdp = (String) msg.getMsg();

        //获取房间信息
        Rooms rooms = RoomUtils.getRooms(cid, null);
        if (rooms == null) {
            Message result = new Message()
                    .setAction("roomInfoError");
            ctx.writeAndFlush(result);
            return;
        }

        //根据角色获取对应用户的WebRtcEndPoint对象
        WebRtcEndpoint endpoint = null;
        if (role.equals("master")) {
            //主播方
            endpoint = rooms.getMaster().getWebRtcEndpoint();
        } else {
            //观看者
            String token = msg.getToken();
            String userJson = (String) JwtUtils.parseJwtToken(token, "user");
            Student student = JSON.parseObject(userJson, Student.class);
            User user = rooms.getSlaves().get(student.getId());
            endpoint = user.getWebRtcEndpoint();
        }

        //设置endPoint候选者监听
        endpoint.addIceCandidateFoundListener(event -> {
            log.debug("[KMS ICE Candidate] 获取到KMS的ICE候选者地址 - {}", event.getCandidate().getCandidate());
            //将候选者信息，传递给客户端
            Message result = new Message()
                    .setAction("iceCandidate")
                    .setMsg(event.getCandidate());
            ctx.writeAndFlush(result);
        });

        //通过endpoint对象，将客户端的提案提交给KMS服务器，返回KMS服务器的应答SDP
        String answer = endpoint.processOffer(offerSdp);

        //将应答SDP回传给客户端
        Message result = new Message()
                .setAction("answerSdp")
                .setMsg(answer);
        ctx.writeAndFlush(result);

        //开启ice的候选者获取
        endpoint.gatherCandidates();
    }
}
